package com.zf.rabbitmq.producer.declare_type;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 使用 AmqpAdmin bean 声明 交换机队列和绑定:
 * <p>
 * 注入 AmqpAdmin 这个bean，实现类是 RabbitAdmin，实际注入的是RabbitAdmin对象，使用其提供的API声明 交换机、队列、绑定：
 * - void declareExchange(org.springframework.amqp.core.Exchange exchange); 声明一个交换机，需要传入一个交换机对象
 * - org.springframework.amqp.core.Queue declareQueue(); 声明一个自动生成名称的交换机 且 exclusive = true, autoDelete=true, durable = false
 * - String declareQueue(org.springframework.amqp.core.Queue queue); 声明一个队列，需要传入一个队列对象
 * - void declareBinding(org.springframework.amqp.core.Binding binding); 声明一个绑定，需要传入一个绑定对象
 * <p>
 * 详见 README.md
 */
@Component
public class DeclareExchangeQueueBindingByAmqpAdmin implements InitializingBean {
    public static final String testAmqpAdminQueueName = "test_amqp_admin_queue";
    public static final String testAmqpAdminDirectExchangeName = "test_amqp_admin_direct_exchange";
    public static final String testAmqpAdminRouteKey = "test_amqp_admin_route_key";

    @Autowired
    private AmqpAdmin amqpAdmin;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 声明一个队列，两种方式
        Queue testQueue = new Queue(testAmqpAdminQueueName, true, false, false, null);
        // Queue testQueue = QueueBuilder.durable("test_amqp_admin_queue").withArguments(null).build();
        amqpAdmin.declareQueue(testQueue);

        // 声明一个交换机，三种方式
        Exchange testExchange = new DirectExchange(testAmqpAdminDirectExchangeName, true, false, null);
        // Exchange testExchange = ExchangeBuilder.directExchange("test_amqp_admin_direct_exchange").durable(true).withArguments(null).build();
        // CustomExchange testExchange = new CustomExchange("test_amqp_admin_direct_exchange", "direct", true, false, null);
        amqpAdmin.declareExchange(testExchange);

        // 声明一个绑定，2种方式
        Binding binding = new Binding(testQueue.getName(), Binding.DestinationType.QUEUE, testExchange.getName(), testAmqpAdminRouteKey, null);
        // Binding binding = BindingBuilder.bind(testQueue).to(testExchange).with("test_amqp_admin_route_key").and(null);
        amqpAdmin.declareBinding(binding);
    }
}
